﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRM_SharePoint_Transports
{
    /// <summary>
    /// SharePoint File / Copy API Support
    /// </summary>
    public static class SharePointFileAPI
    {
        /// <summary>
        /// Uploads a file to SharePoint
        /// </summary>
        /// <param name="destinationURL"></param>
        /// <param name="serviceUrl"></param>
        /// <param name="explicitUser"></param>
        /// <param name="explicitPassword"></param>
        /// <param name="timeOut"></param>
        /// <param name="dal"></param>
        /// <param name="fileName"></param>
        /// <param name="properties"></param>
        /// <param name="fileData"></param>
        public static void UploadFile(string destinationURL, string serviceUrl, string explicitUser, string explicitPassword, int timeOut, BlueIntegrator.DAL.DALBase dal, CRM_SharePoint_Transports.SPCopy.FieldInformation[] properties, byte[] fileData)
        {
            SPCopy.Copy copy = new SPCopy.Copy();
            if (explicitUser == null)
                copy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            else
                copy.Credentials = new System.Net.NetworkCredential(BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(dal, explicitUser), BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(dal, BlueIntegrator.Helpers.Encryption.DecryptString(explicitPassword, "SSIS")));

            if (serviceUrl.EndsWith("/"))
                serviceUrl = serviceUrl.Substring(0, serviceUrl.Length - 1);

            if (!serviceUrl.ToLower().EndsWith("asmx"))
            {
                if (serviceUrl.ToLower().IndexOf("_vti_bin") < 0)
                    copy.Url = serviceUrl + "/_vti_bin/copy.asmx";
                else
                    copy.Url = serviceUrl + "/copy.asmx";
            }

            destinationURL = BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(dal, destinationURL);

            string[] destinationUrls = { destinationURL };

            var copyResult = new CRM_SharePoint_Transports.SPCopy.CopyResult(); 
            CRM_SharePoint_Transports.SPCopy.CopyResult[] copyResults = { copyResult }; 
            copy.CopyIntoItems(destinationURL, destinationUrls, properties, fileData, out copyResults);

            if (copyResult.ErrorCode != SPCopy.CopyErrorCode.Success)
            {
                throw new Exception("Error uploading file to SharPoint location " + destinationURL + " : " + copyResult.ErrorCode.ToString() + " : " + copyResult.ErrorMessage);
            }
        }
    }
}
